#include "../inc/http.h"

extern struct mg_mgr mgr;
extern struct mg_connection *c;
//struct mg_connection *ws;
int flag = 1;
//static void on_flv_send(struct mg_connection *nc, int ev, void *p) {
//    char* hello = "hello";
//        //mg_send_websocket_frame(ws, WEBSOCKET_OP_TEXT, hello, strlen(hello));
//    mg_send_websocket_frame(ws, WEBSOCKET_OP_TEXT, hello, strlen(hello));
//}
//void* send_thread_func(void *arg)
//{
//    char* hello = "hello";
//    while(1)
//    {
//        mg_send_websocket_frame(ws, WEBSOCKET_OP_TEXT, hello, strlen(hello));
//        mg_broadcast(&mgr, on_flv_send, hello, sizeof(hello));
//
//        //sleep();
//    }
//}
/// 分别建立两个回调
void handle_upload(struct mg_connection *nc, int ev, void *pp)
{
    //
    struct http_message* hm = (struct http_message*)pp;
//    std::cout << hm->query_string.p <<std::endl;
    if(ev == MG_EV_CLOSE)
        return;
    if(hm->query_string.len == 0)
        return;
    // 本地终端调试
    std::cout << "Hello!" << std::endl;
    // 发送的字符数据
    char out[80*1024] = "hello";
    mg_printf(nc, "HTTP/1.1 200 OK\r\n");
    mg_printf(nc, "Content-Length: %lu\r\n\r\n", strlen(out));
    mg_printf(nc, out);
    nc->flags |= MG_F_SEND_AND_CLOSE;
}



/// 声明http服务
static struct mg_serve_http_opts s_http_server_opts;
/// 建立一个标准句柄
static void ev_handler(struct mg_connection *nc, int ev, void *p) {
    // 判断事件
    switch (ev) {
        // HTTP请求
        case MG_EV_HTTP_REQUEST: {
            std::cout << "1!" << std::endl;
            struct http_message *hm = (struct http_message *) p;
          //  printf("MG_EV_WEBSOCKET_HANDSHAKE_REQUEST [%.*s], nc:%p, user_data:%p\n"
                  //  , (int) hm->uri.len, hm->uri.p, nc, nc->user_data);
           // std::cout << hm->uri.p << std::endl;
            mg_serve_http(nc, (struct http_message *) p, s_http_server_opts);

            break;
        }

        case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: {
            std::cout << "2!" << std::endl;


            break;
        }
        // 不需要
        case MG_EV_WEBSOCKET_FRAME: {
            std::cout << "3!" << std::endl;


            break;
        }

        case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {


        }

        case MG_EV_CLOSE:{
            std::cout << "4!" << std::endl;
            break;
        }

        default:
            break;
    }
}

int my_http_init(void)
{
    // 初始化mongoose
    mg_mgr_init(&mgr, NULL);
    // 绑定一个http端口
    c = mg_bind(&mgr, "8001", ev_handler);
//    ws = mg_bind(&mgr, "8002", ev_handler);
    if (c == NULL) {
        std::cout << "error!" << std::endl;
        return 1;
    }

//    if (ws == NULL) {
//        std::cout << "error!" << std::endl;
//        return 1;
//    }
    mg_set_protocol_http_websocket(c);
//    mg_set_protocol_http_websocket(ws);
    s_http_server_opts.document_root = "../tmp";
    std::cout << "finish_http_init!" << std::endl;

//    mg_register_http_endpoint(c, "/upload", handle_upload MG_UD_ARG(NULL));
    return 0;
}
